package pl.edu.pw.perg.compinfodb.dao;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GenericSpringDAO<T> extends HibernateDaoSupport implements
		IGenericDAO<T> {

	private Class<T> persistentClass;

	public GenericSpringDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	/* (non-Javadoc)
	 * @see pl.edu.pw.perg.compinfodb.dao.IGenericDAO#getPersistentClass()
	 */
	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	/* (non-Javadoc)
	 * @see pl.edu.pw.perg.compinfodb.dao.IGenericDAO#findById(java.lang.Long)
	 */
	@SuppressWarnings("unchecked")
	public T findById(Long id) {
		return (T) getHibernateTemplate().load(getPersistentClass(), id);
	}

	/* (non-Javadoc)
	 * @see pl.edu.pw.perg.compinfodb.dao.IGenericDAO#findAll()
	 */
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return findByCriteria();
	}

	/* (non-Javadoc)
	 * @see pl.edu.pw.perg.compinfodb.dao.IGenericDAO#findByExample(T, java.lang.String[])
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		crit.add(example);
		return crit.list();
	}

	//
	//    @SuppressWarnings("unchecked")
	//    public T makePersistent(T entity) {
	//        getSession().saveOrUpdate(entity);
	//        return entity;
	//    }
	//
	//    public void makeTransient(T entity) {
	//        getSession().delete(entity);
	//    }

	/* (non-Javadoc)
	 * @see pl.edu.pw.perg.compinfodb.dao.IGenericDAO#flush()
	 */
	public void flush() {
		getSession().flush();
	}

	/* (non-Javadoc)
	 * @see pl.edu.pw.perg.compinfodb.dao.IGenericDAO#clear()
	 */
	public void clear() {
		getSession().clear();
	}

	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

	public void saveAll(Collection<T> items) {
		for (T t : items) {
			getSession().saveOrUpdate(t);
		}
	}

	public void save(T object) {
//		getSession().save(object);
//		getSession().flush();
		getSession().persist(object);
	}

    public void deleteAll(){
//    do nothing
    }
}
